package com.ruoyi.framework.shiro.api;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.BearerToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 移动端或小程序 API 接口认证过滤器
 * 
 * @author ruoyi
 */
public class ApiAuthenticationFilter extends AuthenticatingFilter {
    
    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String authorization = httpRequest.getHeader("Authorization");
        if (authorization != null && authorization.startsWith("Bearer ")) {
            String token = authorization.substring(7);
            return new BearerToken(token);
        }
        return null;
    }
    
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        AuthenticationToken token = createToken(request, response);
        if (token == null) {
            response401(request, response);
            return false;
        }
        try {
            return executeLogin(request, response);
        } catch (AuthenticationException e) {
            response401(request, response);
            return false;
        }
    }
    
    private void response401(ServletRequest request, ServletResponse response) throws IOException {
        WebUtils.toHttp(response).sendError(401, "未授权的访问");
    }
}
